import httpApi from '@/common/http.api.js'

class Queue {
	aliyunPath = 'https://yuyin-online.oss-cn-shanghai.aliyuncs.com'
	constructor() {
	    
	}
	addTask(src, option) {
		this.toast(`${option.name}的视频已提交`);
		this.startCompressVideo(src, option)
	}
	startCompressVideo(src, option) {
		uni.compressVideo({
			src,
			quality: 'medium',
			bitrate: 3000,
			fps: 60,
			resolution: 0.5,
			success: res => {
				this.startUpload(res.tempFilePath, option)
			},
			fail: err => {
				console.log('3', err);
			}
		})
	}
	startUpload(videoSrc, option) {
		try{
			let fileName = this.getFileName(option.file, videoSrc);
			this.fileUpload('video', videoSrc, fileName, option)
		}catch(e){
			console.log(e);
		}
	}
	getFileName(file, filename) {
		return (
			file + Math.random().toString(36).substring(3, 20) + new Date().getTime() + this.getSuffix(filename)
		)
	}
	getSuffix(filename) {
		let pos = filename.lastIndexOf('.')
		let suffix = ''
		if (pos != -1) {
			suffix = filename.substring(pos)
		}
		return suffix
	}
	fileUpload(fileType, filePath, key, option) {
		try{
			const formData = {
				key,
				policy: option.data.policy,
				OSSAccessKeyId: option.data.accessid,
				signature: option.data.signature,
				success_action_status: '200'
			}
			uni.uploadFile({
				url: this.aliyunPath,
				filePath,
				fileType,
				name: 'file',
				formData,
				success: async res => {
					const params = {
						id: option.id,
						video: `/${key}`
					}
					let _res = await this.getApi(httpApi.allApi.upload_video, params, 'POST', option)
					console.log(_res);
					this.toast(`${option.name}的视频上传完毕！`)
				},
				fail: err => {
					this.toast('阿里云上传失败，请联系管理员')
				}
			});
		}catch(e){
			console.log(e);
		}
	}
	getApi(url, data = {}, method = 'GET', option) {
		return new Promise((reslove, reject) => {
			uni.request({
				url: `${httpApi.allApi.baseUrl}${url}`,
				method,
				timeout: 30000,
				data,
				header: {
					'authtoken': option.token
				},
				success: res => {
					reslove(res.data)
				},
				fail(err) {
					reject(err)
				},
				complete() {
					uni.hideLoading()
				}
			})
		})
	}
	toast(msg) {
		// #ifdef APP
		plus.nativeUI.toast(msg);
		// #endif
	}
}

export {
	Queue
}